/*
 * ADC.cc
 *
 *  Created on: Mar 24, 2012
 *      Author: mscuser
 */

#include <string>
#include <stdio.h>
#include <vector>
#include <stdlib.h>
#include "ADC.h"
#include"FaultManager.h"
#include"ErrorManager.h"
#include"config.h"


ADC objDriverAtrialSensor("atrial.csv", enAtrialSensor);
ADC objDriverVentricularSensor("ventricular.csv", enVentricularSensor);

ADC objDriverReduntantAtrialSensor("atrialreduntant.csv", enReduntantAtrialSensor);
ADC objDriverReduntantVentricularSensor("ventricularreduntant.csv", enReduntantVentricularSensor);

int ADC::Read(int id){
	std::string line;
	std::vector<int> v;
	int ret = 0;
	printf("ADC::Read - Driver id = %d", driver_id);

	if(!pfilestream.is_open() ){ //sensor is faulty, not able to sense
		objFaultManager.SetFault(driver_id,TRUE);
		return 0;
	}

	bool valid_line = false;
	if(std::getline(pfilestream, line)){
		valid_line = true;
	}else if(pfilestream.eof()){
#ifndef PACE_DEBUG
		//printf("===============EOF=============\n");
		// If we already reach the EOF, start from the beginning again
		pfilestream.clear();
		pfilestream.seekg (0, std::ios::beg);
		if(std::getline(pfilestream, line)){
			valid_line = true;
		}
#else
		valid_line = false;
#endif
	}else{
		valid_line = false;
	}

	if(valid_line){
		//printf("      valid_line - ");
		std::istringstream iss(line);
		int n;
		iss >> n; // read each number in line
		v.push_back(n);
		//Csv_Data;
		//printf("Value = %d\n",  v.at(0));
		ret = v.at(0);
	}else{
		ret = -1;
	}
	printf("Value = %d\n",  ret);
	return ret;
}

void ADC::Write(int id, int value){


}

void ADC::Init(int id, int value){

}

ADC::ADC(char* filename, DEVICE_ID_TYPE id){
	//std::ifstream myfile (filename);
   pfilestream.open (filename, std::ifstream::in);
   driver_id = id;
}

ADC::~ADC(){
	if(pfilestream.is_open() ){
		pfilestream.close();
	}
}
